package com.material.vtool.controller;

import com.google.common.collect.Maps;
import com.material.vtool.entity.BTeamInfoEntity;
import com.material.vtool.entity.BTeamRelationEntity;
import com.material.vtool.entity.combinedEntity.CombinedTeamMemberEntity;
import com.material.vtool.entity.combinedEntity.UserTeamEntity;
import com.material.vtool.entity.reqEntity.InviteJoinTeamReqBean;
import com.material.vtool.entity.reqEntity.SearchTeamMemberEntity;
import com.material.vtool.entity.reqEntity.TeamMemberEntity;
import com.material.vtool.entity.reqEntity.TeamMemberReqBean;
import com.material.vtool.entity.respEntity.RespData;
import com.material.vtool.entity.respEntity.ReturnCode;
import com.material.vtool.service.TeamInfoService;
import com.material.vtool.service.TeamRelationService;
import com.material.vtool.utils.DateUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;

/**
 * 团队成员
 */
@RestController
@RequestMapping("/teamMember")
public class TeamRelationController {
    @Autowired
    private TeamRelationService teamRelationService;

    /**
     * 搜索团队成员
     * @param searchTeamMemberEntity 查询条件
     * @return
     */
    @PostMapping(value = "/searchTeamMember", produces = "application/json;charset=UTF-8")
    public RespData searchTeamMember(@RequestBody SearchTeamMemberEntity searchTeamMemberEntity) {
        if (searchTeamMemberEntity == null || searchTeamMemberEntity.getTeamId() == null) {
            RespData respData = new RespData();
            respData.setCode(ReturnCode.CLIENT_ERROR);
            respData.setMsg("参数错误");
            return respData;
        }
        Integer teamId = searchTeamMemberEntity.getTeamId();
        String key = searchTeamMemberEntity.getKey();

        List<CombinedTeamMemberEntity> list = teamRelationService.getTeamMemberListByKey(teamId, key);
        // 获取团队成员数量
        int teamMemberCount = teamRelationService.getTeamMemberByKeyCount(teamId, key);

        HashMap<String, Object> resultMap = Maps.newHashMapWithExpectedSize(10);
        resultMap.put("teamMember", list);
        resultMap.put("teamMemberCount", teamMemberCount);

        RespData respData = new RespData();
        respData.setCode(ReturnCode.NORMAL_SUCC);
        respData.setMsg("成功");
        respData.setData(resultMap);
        return respData;
    }

    /**
     * 获取团队的成员信息
     * @param teamMemberReqBean 团队实体
     * @return
     */
    @PostMapping(value = "/getTeamMember", produces = "application/json;charset=UTF-8")
    public RespData getTeamMember(@RequestBody TeamMemberReqBean teamMemberReqBean) {
        if (teamMemberReqBean == null || teamMemberReqBean.getTeamId() == null || teamMemberReqBean.getTeamId().intValue() <= 0) {
            RespData respData = new RespData();
            respData.setCode(ReturnCode.CLIENT_ERROR);
            respData.setMsg("参数错误");
            return respData;
        }
        Integer teamId = teamMemberReqBean.getTeamId();

        List<CombinedTeamMemberEntity> list = teamRelationService.getTeamMemberList(teamId);
        // 获取团队成员数量
        int teamMemberCount = teamRelationService.getTeamMemberCount(teamId);

        HashMap<String, Object> resultMap = Maps.newHashMapWithExpectedSize(10);
        resultMap.put("teamMember", list);
        resultMap.put("teamMemberCount", teamMemberCount);

        RespData respData = new RespData();
        respData.setCode(ReturnCode.NORMAL_SUCC);
        respData.setMsg("成功");
        respData.setData(resultMap);
        return respData;
    }

    /**
     * 加入团队：用户接受邀请加入团队
     * @param userId 用户ID
     * @param inviteJoinTeamReqBean 邀请用户加入团队实体
     * @return
     */
    @PostMapping(value = "/inviteJoinTeam", produces = "application/json;charset=UTF-8")
    public RespData inviteJoinTeam(@RequestHeader("userId") String userId, @RequestBody InviteJoinTeamReqBean inviteJoinTeamReqBean) {
        if (inviteJoinTeamReqBean == null || inviteJoinTeamReqBean.getTeamId() == null || inviteJoinTeamReqBean.getTeamId().intValue() <= 0
            || inviteJoinTeamReqBean.getInviterId() == null || inviteJoinTeamReqBean.getInviterId().intValue() <= 0) {
            RespData respData = new RespData();
            respData.setCode(ReturnCode.CLIENT_ERROR);
            respData.setMsg("参数异常");
            return respData;
        }

        Integer teamMemberId = Integer.valueOf(userId);// 要加入团队的成员ID
        Integer teamId = inviteJoinTeamReqBean.getTeamId();// 团队ID
        Integer inviterId = inviteJoinTeamReqBean.getInviterId();// 邀请人ID

        // 判断该用户之前是否加入过团队
        BTeamRelationEntity teamMember = teamRelationService.getTeamMember(teamMemberId, teamId);

        BTeamRelationEntity bTeamRelationEntity = new BTeamRelationEntity();
        bTeamRelationEntity.setUserId(teamMemberId);
        bTeamRelationEntity.setTeamId(teamId);
        bTeamRelationEntity.setInviterId(inviterId);
        bTeamRelationEntity.setUserFlag(Integer.valueOf(1));// 设置为活跃团队

        if (teamMember != null) {
            if (teamMember.getUserTeamStatus() != null && teamMember.getUserTeamStatus().intValue() == 0) {
                bTeamRelationEntity.setUserTeamStatus(Integer.valueOf(1));
                bTeamRelationEntity.setModifyTime(DateUtil.getCurDate());
                teamRelationService.updateTeamMember(bTeamRelationEntity); // 存在，更新
            } else if (teamMember.getUserTeamStatus() != null && teamMember.getUserTeamStatus().intValue() == 1) {
                RespData respData = new RespData();
                respData.setCode(ReturnCode.TEAM_MEMBER_EXISTS);
                respData.setMsg("用户已加入该团队");
                return respData;
            }
        } else {
            bTeamRelationEntity.setCreateTime(DateUtil.getCurDate());
            teamRelationService.saveTeamRelation(bTeamRelationEntity); // 不存在，新增
        }

        RespData respData = new RespData();
        respData.setCode(ReturnCode.NORMAL_SUCC);
        respData.setMsg("成功");
        return respData;
    }

    /**
     * 加入团队：用户自主加入团队
     * @param userId 用户ID
     * @param teamMemberReqBean 请求实体
     * @return
     */
    @PostMapping(value = "/joinTeam", produces = "application/json;charset=UTF-8")
    public RespData joinTeam(@RequestHeader("userId") String userId, @RequestBody TeamMemberReqBean teamMemberReqBean) {
        if (teamMemberReqBean == null || teamMemberReqBean.getTeamId() == null || teamMemberReqBean.getTeamId().intValue() <= 0) {
            RespData respData = new RespData();
            respData.setCode(ReturnCode.CLIENT_ERROR);
            respData.setMsg("参数异常");
            return respData;
        }

        Integer teamMemberId = Integer.valueOf(userId);// 要加入团队的成员ID
        Integer teamId = teamMemberReqBean.getTeamId();// 团队ID

        // 判断该用户之前是否加入过团队
        BTeamRelationEntity teamMember = teamRelationService.getTeamMember(teamMemberId, teamId);

        BTeamRelationEntity bTeamRelationEntity = new BTeamRelationEntity();
        bTeamRelationEntity.setUserId(teamMemberId);
        bTeamRelationEntity.setTeamId(teamId);
        bTeamRelationEntity.setUserFlag(Integer.valueOf(1));// 设置为活跃团队

        if (teamMember != null) {
            if (teamMember.getUserTeamStatus() != null && teamMember.getUserTeamStatus().intValue() == 0) {
                bTeamRelationEntity.setUserTeamStatus(Integer.valueOf(1));
                bTeamRelationEntity.setModifyTime(DateUtil.getCurDate());
                teamRelationService.updateTeamMember(bTeamRelationEntity); // 存在，更新
            } else if (teamMember.getUserTeamStatus() != null && teamMember.getUserTeamStatus().intValue() == 1) {
                RespData respData = new RespData();
                respData.setCode(ReturnCode.TEAM_MEMBER_EXISTS);
                respData.setMsg("用户已加入该团队");
                return respData;
            }
        } else {
            bTeamRelationEntity.setCreateTime(DateUtil.getCurDate());
            teamRelationService.saveTeamRelation(bTeamRelationEntity); // 不存在，新增
        }

        RespData respData = new RespData();
        respData.setCode(ReturnCode.NORMAL_SUCC);
        respData.setMsg("成功");
        return respData;
    }

    /**
     * 设置成员为管理员
     * @param teamMemberEntity 用户成员实体
     * @return
     */
    @PostMapping(value = "/updateTeamMember", produces = "application/json;charset=UTF-8")
    public RespData updateTeamMember(@RequestBody TeamMemberEntity teamMemberEntity) {
        if (teamMemberEntity == null || teamMemberEntity.getTeamId() == null || teamMemberEntity.getTeamMemberId() == null) {
            RespData respData = new RespData();
            respData.setCode(ReturnCode.CLIENT_ERROR);
            respData.setMsg("参数错误");
            return respData;
        }

        BTeamRelationEntity bTeamRelationEntity = new BTeamRelationEntity();
        bTeamRelationEntity.setUserId(teamMemberEntity.getTeamMemberId());
        bTeamRelationEntity.setTeamId(teamMemberEntity.getTeamId());
        bTeamRelationEntity.setTeamRole(1);
        bTeamRelationEntity.setModifyTime(DateUtil.getCurDate());
        teamRelationService.updateTeamMember(bTeamRelationEntity);

        RespData respData = new RespData();
        respData.setCode(ReturnCode.NORMAL_SUCC);
        respData.setMsg("成功");
        return respData;
    }

    /**
     * 退出团队
     * @param teamMemberEntity 用户成员实体
     * @return
     */
    @PostMapping(value = "/exitTeam", produces = "application/json;charset=UTF-8")
    public RespData exitTeam(@RequestBody TeamMemberEntity teamMemberEntity) {
        if (teamMemberEntity == null || teamMemberEntity.getTeamId() == null || teamMemberEntity.getTeamMemberId() == null) {
            RespData respData = new RespData();
            respData.setCode(ReturnCode.CLIENT_ERROR);
            respData.setMsg("参数错误");
            return respData;
        }

        teamRelationService.exitTeam(teamMemberEntity.getTeamMemberId(), teamMemberEntity.getTeamId());

        RespData respData = new RespData();
        respData.setCode(ReturnCode.NORMAL_SUCC);
        respData.setMsg("成功");
        return respData;
    }

    /**
     * 获取用户的团队列表
     * @param userId 用户ID
     * @return
     */
    @GetMapping(value = "/userTeamList", produces = "application/json;charset=UTF-8")
    public RespData userTeamList(@RequestHeader("userId") String userId) {
        List<UserTeamEntity> userTeamList = teamRelationService.getUserTeamList(Integer.valueOf(userId));

        HashMap<String, Object> resultMap = Maps.newHashMapWithExpectedSize(10);
        resultMap.put("userTeamList", userTeamList);

        RespData respData = new RespData();
        respData.setCode(ReturnCode.NORMAL_SUCC);
        respData.setMsg("成功");
        respData.setData(resultMap);
        return respData;
    }

    /**
     * 获取用户的活跃团队
     * @param userId 用户ID
     * @return
     */
    @GetMapping(value = "/userActiveTeamInfo", produces = "application/json;charset=UTF-8")
    public RespData userActiveTeamInfo(@RequestHeader("userId") String userId) {
        boolean isExist = false;// 是否存在活跃团队
//        List<CombinedTeamMemberEntity> list = null;
//        int teamMemberCount = 0;
        Integer teamId = null;
        String teamName = "";

        Integer currentUserId = Integer.valueOf(userId);

        // 获取当前用户的活跃团队
        BTeamInfoEntity bTeamInfoEntity = teamRelationService.getUserActiveTeamInfo(currentUserId);

        if (bTeamInfoEntity != null && bTeamInfoEntity.getId() != null && bTeamInfoEntity.getId().intValue() > 0) {
            teamId = bTeamInfoEntity.getId();// 团队ID
            teamName = bTeamInfoEntity.getTeamName();// 团队名称

            isExist = true;
            // 获取团队成员列表
//            list = teamRelationService.getTeamMemberList(teamId);
            // 获取团队成员数量
//            teamMemberCount = teamRelationService.getTeamMemberCount(teamId);
        }

        HashMap<String, Object> resultMap = Maps.newHashMapWithExpectedSize(10);
        resultMap.put("isExist", isExist);// 是否存在活跃团队
//        resultMap.put("teamMember", list);
//        resultMap.put("teamMemberCount", teamMemberCount);
        resultMap.put("teamId", teamId);
        resultMap.put("teamName", teamName);

        RespData respData = new RespData();
        respData.setCode(ReturnCode.NORMAL_SUCC);
        respData.setMsg("成功");
        respData.setData(resultMap);
        return respData;
    }

    /**
     * 切换团队:更新用户的活跃团队
     * @param userId 用户ID
     * @param teamMemberReqBean 团队实体
     * @return
     */
    @PostMapping(value = "/updateActiveTeam", produces = "application/json;charset=UTF-8")
    public RespData updateActiveTeam(@RequestHeader("userId") String userId, @RequestBody TeamMemberReqBean teamMemberReqBean) {
        if (teamMemberReqBean == null || teamMemberReqBean.getTeamId() == null || teamMemberReqBean.getTeamId().intValue() <= 0) {
            RespData respData = new RespData();
            respData.setCode(ReturnCode.CLIENT_ERROR);
            respData.setMsg("参数错误");
            return respData;
        }
        Integer teamId = teamMemberReqBean.getTeamId();

        teamRelationService.updateActiveTeam(Integer.valueOf(userId), teamId);

        RespData respData = new RespData();
        respData.setCode(ReturnCode.NORMAL_SUCC);
        respData.setMsg("成功");
        return respData;
    }
}
